<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>layui</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="/lib/layui-v2.6.3/css/layui.css" media="all">
    <link rel="stylesheet" href="/css/public.css" media="all">
</head>
<body>
<div class="layuimini-container" id="app">
    <div class="layuimini-main">
        <fieldset class="layui-elem-field layui-field-title" style="margin-top: 20px;">
            <legend>{{id?'编辑':'添加'}}区服</legend>
        </fieldset>
        <form class="layui-form" action="" lay-filter="example">


            <div class="layui-form-item">
                <label class="layui-form-label">编号</label>
                <div class="layui-input-block">
                    <input type="text" name="num" lay-verify="required" placeholder="请输入" autocomplete="off" class="layui-input" >
                </div>
            </div>

            <div class="layui-form-item" style="width: 600px;">
                <label class="layui-form-label">规则ID:</label>
                <div class="layui-input-inline" style="width: 300px">
                    <select name="TypeId" class="layui-select" lay-search=""  lay-filter="SelectChange" style="width: 300px">
                        <option value="">全部</option>
                        <option v-for="(item, index) in activeatrr" :key="index" :value="item.id">
                            {{ item.id }} - {{ item.name }}
                        </option>
                    </select>
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">名称</label>
                <div class="layui-input-block">
                    <input type="text" name="name" v-model="formData.name"  id="name" placeholder="请输入" autocomplete="off" class="layui-input">
                </div>
            </div>



            <div class="layui-form-item">
                <label class="layui-form-label">后台备注</label>
                <div class="layui-input-block">
                    <input type="text" name="rmark"  placeholder="请输入" autocomplete="off" class="layui-input">
                </div>
            </div>


            <div class="layui-form-item" >
                <label class="layui-form-label">服分组</label>
                <div class="layui-input-inline">
                    <div id="serverGroup"></div>
                </div>
            </div>

            <div class="layui-form-item" >
                <label class="layui-form-label">服务器列表</label>
                <div class="layui-input-inline">
                    <div id="ServerIds"  :class="{ 'disabled': isServerListDisabled }"></div>
                </div>
            </div>

            <div class="layui-form-item" >
                <label class="layui-form-label">服务器选中项</label>
                <div class="layui-input-block">
                    <input type="text" name="ServerList"  id="serverList" placeholder="请输入" autocomplete="off" class="layui-input">
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">服务器类型</label>
                <div class="layui-input-block">
                    <select name="ServerType" class="layui-input" v-model="formData.ServerType" :disabled="hasSelected" lay-filter="serverType">
                        <option value="1" :selected="(!id || formData.ServerType == 1)">全服</option>
                        <option value="3">单服</option>
                    </select>
                </div>
            </div>




            <div class="layui-form-item">
                <label class="layui-form-label">时间类型</label>
                <div class="layui-input-block">
                    <select name="TimeType" class="layui-select" v-model="formData.TimeType">
                        <option value="1">开服时间(秒)</option>
                        <option value="2">自然时间</option>
                        <option value="3">创角时间(秒)</option>
                        <option value="4">合服时间(秒)</option>
                        <option value="5">每周时间</option>
                    </select>
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">开启时间</label>
                <div class="layui-input-block">
                    <input type="text" name="TimeOpen" id="TimeOpen"
                           placeholder="开启时间" autocomplete="off" class="layui-input" />
                </div>
            </div>


            <div class="layui-form-item">
                <label class="layui-form-label">结束时间</label>
                <div class="layui-input-block">
                    <input type="text" name="TimeEnd" id="TimeEnd"
                           placeholder="结束时间" autocomplete="off" class="layui-input" />
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">轮转设置</label>
                <div class="layui-input-block">
                    <select name="LoopType" id="loopType" class="layui-select" lay-filter="loopType"  v-model="formData.LoopType">
                        <option value="0">不循环</option>
                        <option value="1">日循环</option>
                        <option value="2">周循环</option>
                        <option value="3">月循环</option>
                    </select>
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">循环周期</label>
                <div class="layui-input-block">
                    <input type="text" name="LoopVal" id="loopVal" placeholder="请输入" autocomplete="off" class="layui-input" :disabled="isLoopValDisabled" v-model="formData.LoopVal">
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">每日限时时间段开始</label>
                <div class="layui-input-block">
                    <input type="text" name="LoopDayTimeLimitStart" id="LoopDayTimeLimitStart"
                           placeholder="每日限时时间段开始" autocomplete="off" class="layui-input" />
                </div>
            </div>




            <div class="layui-form-item">
                <label class="layui-form-label">每日限时时间段结束</label>
                <div class="layui-input-block">
                    <input type="text" name="LoopDayTimeLimitEnd" id="LoopDayTimeLimitEnd"
                           placeholder="每日限时时间段结束" autocomplete="off" class="layui-input" />
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">活动每日刷新时间</label>
                <div class="layui-input-block">
                    <input type="text" name="DayRefreshTime" id="DayRefreshTime"
                           placeholder="活动每日刷新时间" autocomplete="off" class="layui-input" />
                </div>
            </div>


            <div class="layui-form-item">
                <label class="layui-form-label">上级UI</label>
                <div class="layui-input-block">
                    <select name="UIInFuncId" class="layui-select" v-model="formData.UIInFuncId">
                        <option value="0">活动界面</option>
                        <option value="1">兑换界面</option>
                        <option value="1001">七日签到</option>
                        <option value="99999">不显示</option>
                    </select>
                </div>
            </div>


            <div class="layui-form-item">
                <label class="layui-form-label">弹出提示(秒)</label>
                <div class="layui-input-block">
                    <input type="text" name="UIInFuncIdParam"  placeholder="请输入(秒)" autocomplete="off" class="layui-input">
                </div>
            </div>




            <div class="layui-form-item">
                <label class="layui-form-label">是否播报</label>
                <div class="layui-input-block">
                    <input type="radio" name="IsSysMsg" value="1" title="播报" class="layui-input" :checked="(!id||formData.IsSysMsg==1)?true:false">
                    <input type="radio" name="IsSysMsg" value="0" title="不播报" class="layui-input">
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">转生要求</label>
                <div class="layui-input-block">
                    <input type="radio" name="Rebirth" value="1" title="转生" class="layui-input" :checked="(!id||formData.Rebirth==1)?true:false">
                    <input type="radio" name="Rebirth" value="0" title="不转生" class="layui-input">
                </div>
            </div>


            <div class="layui-form-item">
                <label class="layui-form-label">互斥活动</label>
                <div class="layui-input-block">
                    <input type="text" name="ExclusionAction"  placeholder="请输入" autocomplete="off" class="layui-input">
                </div>
            </div>




            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button class="layui-btn" lay-submit="" lay-filter="demo1">立即提交</button>
                    <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                </div>
            </div>
        </form>

    </div>
</div>
<script src="/lib/layui-v2.6.3/layui.js" charset="utf-8"></script>
<script src="/js/common.js?v=5" charset="utf-8"></script>
<script src="/xm-select-v1.2.4/xm-select.js"></script>

<!-- 注意：如果你直接复制所有代码到本地，上述js路径需要改成你本地的 -->
<script>
    var Id = urlParam('id')
    var form = null;
    var serverGroup = getEnum('serverGroup')
    var activeatrr = getEnum('activeatrr')
    var services = JSON.parse(localStorage.getItem('services'))

    new Vue({
        el:"#app",
        data:{
            id:Id,
            serverGroups:[],
            formData:{
                activeatrr:activeatrr,
                show:null,
                status:null,
                busy_status:null,
                pay_status:null,
                white_status:"0",
                LoopType: '0', // 默认值
                LoopVal: '0' ,// 默认填入 0
                ServerType: '1', // 确保这里是字符串
                name:null
            },
            isLoopValDisabled: true,
            hasSelected: false ,// 新增属性,
            uniqueServerIds: [], // 定义 uniqueServerIds
            isServerListDisabled: false, // 控制服务器列表是否禁用



        },
        updated:function(){
            form.render();
        },
        methods:{
            getActiveNameById:function(id){
                for(var k in activeatrr){
                    var v = activeatrr[k];
                    if (v.id == id){
                        return v.name;
                    }
                }
                return '无此活动';
            },

            handleServerTypeChange() {
                console.log('触发了',this.formData.ServerType);

                if (this.formData.ServerType === '1') { // 当选择全服时
                    // 清空服分组选择
                    var serverGroupSelect = xmSelect.get('#serverGroup');
                    if (serverGroupSelect) {
                        serverGroupSelect.setValue([]);
                    }
                    
                    // 清空服务器列表选择
                    var serverIdsSelect = xmSelect.get('#ServerIds');
                    if (serverIdsSelect) {
                        serverIdsSelect.setValue([]);
                    }
                    
                    // 清空服务器选中项输入框
                    document.getElementById('serverList').value = '';
                    
                    // 重置相关状态
                    this.uniqueServerIds = [];
                    this.isServerListDisabled = false;
                    this.hasSelected = false;
                }
            },

            handleLoopTypeChange() {
                console.log('触发了',this.formData.LoopType);
                if (this.formData.LoopType === '0') {
                    this.formData.LoopVal = '0'; // 设置 LoopVal 为 0
                    this.isLoopValDisabled = true; // 禁用输入
                } else {
                    this.isLoopValDisabled = false; // 启用输入
                    if (!this.formData.LoopVal || this.formData.LoopVal === '0') {
                        this.formData.LoopVal = ''; // 清空 LoopVal
                    }
                }
            },

            initializeSelect() {
                var serverSg = [];
                for(var k in services){
                    var v = services[k];
                    serverSg.push({
                        name:v.name,
                        value:v.server_id,
                    })
                }



                xmSelect.render({
                    el: '#ServerIds',
                    name: "ServerIds",
                    language: 'zn',
                    data: serverSg,
                    on: (data) => {
                        console.log('DATA:', data); // 打印选中的数据

                        var selectedValues = []; // 初始化一个空数组

                        data.arr.forEach((item) => {
                            selectedValues.push(item.value); // 将 item.value 添加到数组中
                        });

                        // 拼接为逗号分隔的字符串
                        var serverListString = selectedValues.join(',');
                        this.$nextTick(() => {
                            document.getElementById('serverList').value = serverListString;
                            document.querySelector('select[name="ServerType"]').removeAttribute('disabled'); // 启用选择框
                        });
                    }
                });
            }
        },
        mounted:function() {
            var _this = this;



            layui.use(['form', 'laydate'], function () {
                form = layui.form;
                var layer = layui.layer, $ = layui.$,laydate=layui.laydate;
                laydate.render({
                    elem: '#TimeOpen', // 绑定元素
                    type: 'datetime', // 日期时间类型
                    trigger: 'click', // 点击触发
                    format: 'yyyy-MM-dd HH:mm:ss' // 设置日期时间格式，包含秒
                });

                laydate.render({
                    elem: '#TimeEnd', // 绑定元素
                    type: 'datetime', // 日期时间类型
                    trigger: 'click', // 点击触发
                    format: 'yyyy-MM-dd HH:mm:ss' // 设置日期时间格式，包含秒
                });

                laydate.render({
                    elem: '#LoopDayTimeLimitStart', // 绑定元素
                    type: 'datetime', // 日期时间类型
                    trigger: 'click', // 点击触发
                    format: 'HH:mm:ss' // 设置日期时间格式，包含秒
                });

                laydate.render({
                    elem: '#LoopDayTimeLimitEnd', // 绑定元素
                    type: 'datetime', // 日期时间类型
                    trigger: 'click', // 点击触发
                    format: 'HH:mm:ss' // 设置日期时间格式，包含秒
                });

                laydate.render({
                    elem: '#DayRefreshTime', // 绑定元素
                    type: 'datetime', // 日期时间类型
                    trigger: 'click', // 点击触发
                    format: 'HH:mm:ss' // 设置日期时间格式，包含秒
                });
                //服务器列表


                //服分组的
                var dataSg = serverGroup.map(function (group) {
                    return {
                        name: group.group_name,
                        value: group.group_id,
                        selected: false // 默认未选中

                    };
                });
                var serverIdsMap = {};
                serverGroup.forEach(function (group) {
                    serverIdsMap[group.group_id] = group.server_ids;
                });


                //服务器分组
                $.get('/admin/serverGroup/paginate',{limit:100},function(res){
                    _this.serverGroups = res.data
                })
                if (Id) {
                    $.get('/admin/activeRuleqdtc/' + Id, {}, function (res) {
                        var data = res.data;
                        _this.formData = data;
                        var waiting = setInterval(function () {
                            if (_this.serverGroups.length>0) {
                                form.val('example', {
                                    "num": data.num,
                                    "name": data.name,
                                    "TypeId": data.TypeId,
                                    "serverGroup": data.serverGroup,
                                    "ServerType": data.ServerType,
                                    "ServerList": data.ServerList,
                                    "TimeType": data.TimeType,
                                    "TimeOpen": data.TimeOpen,
                                    "TimeEnd": data.TimeEnd,
                                    "LoopType": data.LoopType,
                                    "LoopVal": data.LoopVal,
                                    "LoopDayTimeLimitStart": data.LoopDayTimeLimitStart,
                                    "LoopDayTimeLimitEnd": data.LoopDayTimeLimitEnd,
                                    "DayRefreshTime": data.DayRefreshTime,
                                    "UIInFuncId": data.UIInFuncId,
                                    "UIInFuncIdParam": data.UIInFuncIdParam,
                                    "IsSysMsg": data.IsSysMsg,
                                    "Rebirth": data.Rebirth,
                                    "ExclusionAction": data.ExclusionAction
                                });


                                if(data.serverGroup){
                                    // 初始化服分组 xmSelect 的值
                                    var selectedGroupIds = data.serverGroup.split(','); // 假设 groupids 是以逗号分隔的字符串

                                    // 更新 dataSg 的选中状态
                                    dataSg.forEach(function (item) {
                                        item.selected = selectedGroupIds.includes(item.value.toString()); // 确保类型一致
                                    });
                                    xmSelect.render({
                                        el: '#serverGroup',
                                        name: "serverGroup",
                                        language: 'zn',
                                        data: dataSg,
                                        on: function(data) {
                                            console.log('DATA:', data); // 打印选中的数据

                                            var selectedServerIds = [];

                                            // 遍历选中的项
                                            data.arr.forEach(function(item) {
                                                var groupId = item.value; // 获取选中的 group_id
                                                if (serverIdsMap[groupId]) {
                                                    selectedServerIds = selectedServerIds.concat(serverIdsMap[groupId]); // 合并对应的 server_ids
                                                }
                                            });


                                            // 拼接为逗号分隔的字符串
                                            _this.uniqueServerIds = Array.from(new Set(selectedServerIds));

                                            var serverListString = this.uniqueServerIds.join(',');

                                            // 使用 this.$nextTick 确保 DOM 更新后再设置值
                                            _this.$nextTick(() => {
                                                document.getElementById('serverList').value = serverListString;
                                                _this.formData.ServerType = _this.uniqueServerIds.length > 0 ? '3' : '1'; // 根据选中项设置类型
                                                _this.initializeSelect();

                                                if (_this.uniqueServerIds.length > 0) {
                                                    document.querySelector('select[name="ServerType"]').setAttribute('disabled', 'disabled'); // 禁用选择框
                                                    _this.isServerListDisabled=true;

                                                }else {
                                                    document.querySelector('select[name="ServerType"]').removeAttribute('disabled'); // 启用选择框
                                                    _this.isServerListDisabled=false;

                                                }

                                            });
                                        }
                                    });
                                }
                                clearInterval(waiting)
                                _this.handleLoopTypeChange(); // 
                                _this.handleServerTypeChange(); // 初始化状态
                            }
                        },1)
                    })
                    //表单初始赋值
                }



                //监听提交
                form.on('submit(demo1)', function (data) {
                    var formData = data.field;

                    // 如果服务器类型是全服，清空 serverGroup
                    if (formData.ServerType === '1') {
                        formData.serverGroup = null;
                        formData.ServerList = null;
                    }

                    console.log('查看传过来的ID',Id)
                    if (Id) {

                        formData._method = 'put';
                        $.post('/admin/activeRuleqdtc/' + Id, formData, function (res) {
                            if (res.code === 0) {
                                layer.msg('success', {icon: 6, time: 500}, function () {
                                    parent.location.reload();//父页面刷新
                                })
                            } else {
                                layer.msg(res.msg, {icon: 5})
                            }
                        })
                    } else { //add
                        $.post('/admin/activeRuleqdtc/add', formData, function (res) {
                            if (res.code === 0) {
                                layer.msg('success', {icon: 6, time: 500}, function () {
                                    parent.location.reload();//父页面刷新
                                })
                            } else {
                                layer.msg(res.msg, {icon: 5})
                            }
                        })
                    }

                    return false;
                });


                form.on('radio(status)',function(data){
                    _this.formData.status = data.value;
                })
                form.render();


                form.on('select(SelectChange)',function(data){
                    var selectId = parseInt(data.value);
                    console.log('当前选择的ID',selectId)
                    console.log('当前选择的data',data)

                    _this.formData.name  = _this.getActiveNameById(selectId);
                })

                // 监听下拉框选择变化
                form.on('select(loopType)', function(data) {
                    console.log('监听下拉框改变值',data.value);
                    _this.formData.LoopType = data.value; // 更新 Vue 数据
                    _this.handleLoopTypeChange(); // 调用处理函数
                });
       
                form.on('select(serverType)', function(data) {
                    console.log('服务器类型改变:', data.value);
                    _this.formData.ServerType = data.value;
                    
                    if (data.value === '1') { // 当选择全服时
                        // 重置 dataSg 的选中状态
                        dataSg.forEach(function(item) {
                            item.selected = false;
                        });

                        // 重新渲染服分组选择器
                        xmSelect.render({
                            el: '#serverGroup',
                            name: "serverGroup",
                            language: 'zn',
                            data: dataSg,
                            on: function(data) {
                                console.log('DATA:', data);
                                var selectedServerIds = [];
                                data.arr.forEach(function(item) {
                                    var groupId = item.value;
                                    if (serverIdsMap[groupId]) {
                                        selectedServerIds = selectedServerIds.concat(serverIdsMap[groupId]);
                                    }
                                });
                                _this.uniqueServerIds = Array.from(new Set(selectedServerIds));
                                var serverListString = _this.uniqueServerIds.join(',');
                                
                                _this.$nextTick(() => {
                                    document.getElementById('serverList').value = serverListString;
                                    _this.formData.ServerType = _this.uniqueServerIds.length > 0 ? '3' : '1';
                                    
                                    if (_this.uniqueServerIds.length > 0) {
                                        document.querySelector('select[name="ServerType"]').setAttribute('disabled', 'disabled');
                                        _this.isServerListDisabled = true;
                                    } else {
                                        document.querySelector('select[name="ServerType"]').removeAttribute('disabled');
                                        _this.isServerListDisabled = false;
                                    }
                                    form.render('select');
                                });
                            }
                        });

                        // 重新渲染服务器列表选择器
                        _this.initializeSelect();
                        
                        // 清空服务器选中项输入框
                        document.getElementById('serverList').value = '';
                        
                        // 重置相关状态
                        _this.uniqueServerIds = [];
                        _this.isServerListDisabled = false;
                        _this.hasSelected = false;
                        
                        // 重新渲染表单
                        form.render();
                    }
                });

                _this.initializeSelect();




            })
        },

    });
</script>


</body>
<style>


    .disabled {
        pointer-events: none; /* 禁用所有指针事件 */
        opacity: 0.6; /* 使元素变得透明 */
    }
</style>
</html>